<template>
  <div>
    <h2>示例1：登录表单示例</h2>
    <FormValidation
        v-model="formData"
        :fields="fields"
        :rules="rules"
        @submit="handleSubmit"
        @validate:success="handleSuccess"
        @validate:fail="handleFail"
    />


    <h2 style="margin-top: 20px;">示例2：注册表单示例</h2>
    <FormValidation
        v-model="regForm"
        :fields="regFields"
        :rules="regRules"
        label-width="120px"
        @submit="handleRegister"
    >
      <template #submit>
        <button type="submit" class="custom-submit">立即注册</button>
      </template>
    </FormValidation>


    <h2 style="margin-top: 20px;">示例3：注册表单示例</h2>
    <FormValidation
        v-model="inlineForm"
        :fields="inlineFields"
        :rules="inlineRules"
        inline
        label-width="80px"
        @change="handleFieldChange"
    />
  </div>

</template>

<script setup>
import {ref} from 'vue'
import FormValidation from '@/components/FormValidation/FormValidation.vue'

const formData = ref({
  username: '',
  password: ''
})

const fields = [
  {name: 'username', label: '用户名', type: 'text'},
  {name: 'password', label: '密码', type: 'password'}
]

const rules = {
  username: [
    'required',
    value => ({
      validator: v => v.length >= 4,
      message: '用户名至少4个字符'
    })
  ],
  password: [
    'required',
    'minLength:6'
  ]
}

const handleSubmit = (formData) => {
  console.log('提交数据:', formData)
}

const handleSuccess = (validData) => {
  console.log('验证成功:', validData)
}

const handleFail = (errors) => {
  console.error('验证失败:', errors)
}

// 示例2
const regForm = ref({
  email: '',
  password: '',
  gender: ''
})

const regFields = [
  { name: 'email', label: '电子邮箱', type: 'text' },
  { name: 'password', label: '设置密码', type: 'password' },
  {
    name: 'gender',
    label: '性别',
    type: 'select',
    options: [
      { value: '', label: '请选择' },
      { value: 'male', label: '男性' },
      { value: 'female', label: '女性' }
    ]
  }
]

const regRules = {
  email: ['required', 'email'],
  password: ['required', 'minLength:8'],
  gender: [v => !!v || '请选择性别']
}

const handleRegister = (formData) => {
  console.log('注册数据:', formData)
}

// 示例3
const inlineForm = ref({
  search: '',
  category: ''
})

const inlineFields = [
  { name: 'search', label: '搜索', type: 'text' },
  {
    name: 'category',
    label: '分类',
    type: 'select',
    options: [
      { value: '', label: '全部' },
      { value: '1', label: '电子产品' },
      { value: '2', label: '图书' }
    ]
  }
]

const inlineRules = {
  search: [v => v.length <= 20 || '搜索词过长']
}

const handleFieldChange = (fieldName, value) => {
  console.log(`字段 ${fieldName} 变更为:`, value)
}
</script>